package com.oa.role.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.oa.entity.TblRight;
import com.oa.entity.TblRole;
import com.oa.role.Biz.RoleBiz;
import com.oa.util.BaseAction;
import com.oa.util.MyStaticConst;

import net.sf.json.JSONObject;

@SuppressWarnings("serial")
public class RoleAction extends BaseAction {
	
	private RoleBiz roleBiz;
	private TblRole tblRole;
	private JSONObject roleJson;

	/**
	 * 数据加载：角色列表
	 * @return SUCCESS
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public String role_list()throws Exception{
		String hql = "From TblRole tr where 1=1";
		List<TblRole> role_list = this.roleBiz.searchData(hql, null);
		request.getSession().setAttribute("role_list", role_list);
		return SUCCESS;
	}
	
	/**
	 * 角色删除
	 * @return SUCCESS
	 * @throws Exception
	 */
	public String role_delete()throws Exception{
		Integer rid = Integer.parseInt(request.getParameter("roleId"));
		roleJson = new JSONObject();
		tblRole = roleBiz.load(rid);
		//获取关联到该角色的用户
		Integer userSize = tblRole.getUsers().size();
		if(userSize==null||userSize<=0){
			roleBiz.delete(tblRole);
		}else{
			roleJson.put("role_delete_msg", "无法删除该角色，存在关联用户！");
		}
		return SUCCESS;
	}
	/**
	 * 跳转角色添加页面
	 * @return SUCCESS
	 * @throws Exception
	 */
	public String role_to_add()throws Exception{
		return SUCCESS;
	}
	/**
	 * 执行角色添加
	 * @return SUCCESS
	 * @throws Exception
	 */
	public String role_do_add()throws Exception{
		this.roleBiz.add(this.tblRole);
		return null;
	}
	/**
	 * 数据合法验证：角色名唯一
	 * @return SUCCESS
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String roleName_IValidatable()throws Exception{
		String hql = "From TblRole tr where 1=1 and tr.roleName=:roleName";
		Map params = new HashMap();
		params.put("roleName", request.getParameter("roleName"));
		List<TblRole> role_list = this.roleBiz.searchData(hql, params);
		roleJson = new JSONObject();
		if(role_list!=null&&role_list.size()>0){
			roleJson.put("roleName_IValidatable_msg", 0);
		}else{
			roleJson.put("roleName_IValidatable_msg", 1);
		}
		return SUCCESS;
	}
	/**
	 * 跳转角色编辑页面
	 * @return SUCCESS
	 * @throws Exception
	 */
	public String role_to_edit()throws Exception{
		//获得权限列表
		String hql = "From TblRight tr where 1=1";
		List<TblRight> rightsList = this.roleBiz.searchData(hql, null);
		//获取角色Id，加载相应角色
		Integer roleId = Integer.parseInt(request.getParameter("roleId"));
		TblRole role = this.roleBiz.load(roleId);
		request.setAttribute("tblRole", role);
		//新建存放角色权限的容器
		Map<TblRight,Map<TblRight,String>> role_rights_map = new HashMap<TblRight,Map<TblRight,String>>();
		List<TblRight> tempList_1 = new ArrayList<TblRight>();
		//抽取父级权限对象，设置为rightsMap_One的key，其他权限对象存入临时容器
		for(TblRight tr_1:rightsList){
			if(tr_1.getRightsParentCode().equals(MyStaticConst.ROOT_MENU)){
				role_rights_map.put(tr_1, null);
			}else{
				tempList_1.add(tr_1);
			}
		}
		//将子级权限的容器中的对象，循环筛选出将其对应到rightsMap_One容器中的value中
		for(TblRight tr_2:role_rights_map.keySet()){
			Map<TblRight,String> tempMap_1 = new HashMap<TblRight,String>();
			for(TblRight tr_3:tempList_1){
				//权限的对象RightsParentCode与key对象的RightsCode相同的
				//存入同一个临时容器 
				if(tr_3.getRightsParentCode().equals(tr_2.getRightsCode())){
					tempMap_1.put(tr_3, MyStaticConst.UNCHECKED);
				}
			}
			//将临时容器存入大容器中
			role_rights_map.put(tr_2, tempMap_1);
		}
		//测试打印输出户
		System.out.println("原始数据[未拆包]：");
		printMap(role_rights_map);
		
		//获取角色列表
		Set<TblRight> rights =  role.getRights_box();
		for(TblRight trr11:rights){
			System.out.println("@$@$"+trr11.getRightsCode());
		}
		/*
		 * 角色存在权限
		 */
		if(rights.size()>0){
			
			for(TblRight tr_4:rights){
				//将已有权限列表中属于父级的筛选出来。
				if(tr_4.getRightsParentCode().equals(MyStaticConst.ROOT_MENU)){
					//与当容器中的key对比
					for(TblRight tr_5:role_rights_map.keySet()){
						if(tr_5.getRightsCode().equals(tr_4.getRightsCode())){
							//获得vlaue中的值
							Map<TblRight,String> map_1 = role_rights_map.get(tr_5);
							Map<TblRight,String> map_2 = new HashMap<TblRight,String>();
							//将value中map容器中的权限对象设置为选中状态
							for(TblRight tr_6:map_1.keySet()){
								map_2.put(tr_6, MyStaticConst.CHECKED);
							}
							//更换大容器中key对应的value
							role_rights_map.put(tr_5, map_2);
						}
					}
				}else{
					for(TblRight tr_6:role_rights_map.keySet()){
						//找到大容器中子级权限RightsParentCode对应的key
						if(tr_6.getRightsCode().equals(tr_4.getRightsParentCode())){
							Map<TblRight,String> map_1 = role_rights_map.get(tr_6);
							//找到子级权限在value集合中的位置
							for(TblRight tr_7:map_1.keySet()){
								if(tr_7.getRightsCode().equals(tr_4.getRightsCode())){
									map_1.put(tr_7, MyStaticConst.CHECKED);
								}
							}
							//替换大容器中原有的value
							role_rights_map.put(tr_6, map_1);
						}
					}
				}
			}
			//测试打印输出户
			System.out.println("处理之后数据：");
			printMap(role_rights_map);
			request.setAttribute("role_rights", 1);
			request.getSession().setAttribute("role_rights_map", role_rights_map);
		}else{
			/*
			 * 角色不存在权限
			 */
			request.setAttribute("role_rights", 0);
			request.getSession().setAttribute("role_rights_map", role_rights_map);
		}
		return SUCCESS;
	}
	public void printMap(Map<TblRight,Map<TblRight,String>> params){
		for(TblRight tr_1 : params.keySet()){
			System.out.print("第一层：[key.pCode]:"+tr_1.getRightsParentCode());
		}
		System.out.println();
		for(Map<TblRight,String> map_1 : params.values()){
			for(TblRight tr_2:map_1.keySet()){
				System.out.print("第三层[key.rCode]："+tr_2.getRightsCode());
			}
			System.out.println();
			for(String s:map_1.values()){
				System.out.print("第三层[value]:"+s);
			}
			System.out.println();
		}
	}
	/**
	 * 角色编辑处理
	 * @return SUCCESS
	 * @throws Exception
	 */
	public String role_do_edit()throws Exception{
		Integer roleId = Integer.parseInt(request.getParameter("roleId"));
		String roleName = request.getParameter("roleName");
		String roleAbstract = request.getParameter("roleAbstract");
		TblRole targetRole = this.roleBiz.load(roleId);
		targetRole.setRoleName(roleName);
		targetRole.setRoleAbstract(roleAbstract);
		return SUCCESS;
	}
	/**
	 * 权限分配
	 * @return SUCCESS
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public String role_add_rights()throws Exception{
		Integer roleId = Integer.parseInt(request.getParameter("roleId"));
		String rightsJson = request.getParameter("rights_codes");
		//将Json字符串转换成Map集合
		Map<String,Object> mapJson = JSONObject.fromObject(rightsJson);
		StringBuffer buff = new StringBuffer();
		//json处理
		for(Entry<String,Object> entry:mapJson.entrySet()){
			String tempValue = entry.getValue().toString();
			if(tempValue.equals("unchecked")){
				//空值，未选中
			}else{
				if(tempValue.equals("check_all")){
					//全选
					buff = buff.length()>0 ? buff.append(","+entry.getKey()) : buff.append(entry.getKey());
				}else{
					//其他
					buff = buff.length()>0 ? buff.append(","+entry.getValue()) : buff.append(entry.getValue());
				}
			}
		}
		//将处理结果拆分成数组
		
		Pattern p = Pattern.compile("[`\\[\\]\"]");
		Matcher m = p.matcher(buff.toString());
		String[] rightsCode_box = m.replaceAll("").trim().split(",");
		this.roleBiz.Role_Assgin_Rights(roleId, rightsCode_box);
		return SUCCESS;
	}
	
	public RoleBiz getRoleBiz() {
		return roleBiz;
	}
	public void setRoleBiz(RoleBiz roleBiz) {
		this.roleBiz = roleBiz;
	}
	public TblRole getTblRole() {
		return tblRole;
	}
	public void setTblRole(TblRole tblRole) {
		this.tblRole = tblRole;
	}
	public JSONObject getRoleJson() {
		return roleJson;
	}
	public void setRoleJson(JSONObject roleJson) {
		this.roleJson = roleJson;
	}
}
